package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.common.StatusCode;
import com.example.demo.dao.UserDao;
import com.example.demo.exception.FileFormatException;
import com.example.demo.model.User;
import com.example.demo.service.AuthService;
import com.example.demo.service.impl.AuthServiceImpl;
import org.apache.ibatis.jdbc.SqlRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Map;
import java.util.UUID;

@CrossOrigin
@RestController
//@RequestMapping("/my")
public class UserController {
    @Autowired
    private AuthService authService;

    private String fileDirectory;

    @PostMapping("/my/login")
    public ResponseEntity<Result<String>> login(@RequestBody Map<String, String> requestBody) {
        String username = requestBody.get("username");
        String password = requestBody.get("password");

        // 从数据库中查找用户
        User user = authService.findByName(username);
        System.out.println(user);
        System.out.println(username);
        System.out.println(password);

        // 验证用户名和密码
        if (user != null && user.getPassword() != null && user.getPassword().equals(password)) {
            return ResponseEntity.ok(new Result<>(true, StatusCode.OK, "登录成功", null));
        } else {
            // 登录失败，返回错误信息
            return ResponseEntity.ok(new Result<>(false, StatusCode.ERROR, "用户名或密码错误", null));
        }
    }

    @PostMapping("/my/register")
    public ResponseEntity<Result<String>> register(@RequestBody Map<String, String> requestBody) {
        String username = requestBody.get("username");
        String password = requestBody.get("password");

        // 检查用户名是否已存在
        User existingUser = authService.findByName(username);
        if (existingUser != null) {
            return ResponseEntity.ok(new Result<>(false, StatusCode.ERROR, "用户名已存在", null));
        }

        // 创建新用户
        User newUser = new User();
        newUser.setName(username);
        newUser.setPassword(password);

        // 插入用户到数据库
        int rowsAffected = authService.insert(newUser);
        if (rowsAffected > 0) {
            return ResponseEntity.ok(new Result<>(true, StatusCode.OK, "注册成功", null));
        } else {
            return ResponseEntity.ok(new Result<>(false, StatusCode.ERROR, "注册失败", null));
        }
    }

    @GetMapping("/my/loginSelectByUsername/{name}")
    public ResponseEntity<Result<User>> getUserInfoByUsername(@PathVariable String name) {
        System.out.println(name);
        User user = authService.findByName(name);
        if (user != null) {
            return ResponseEntity.ok(new Result<>(true, StatusCode.OK, "获取用户信息成功", user));
        } else {
            return ResponseEntity.ok(new Result<>(false, StatusCode.ERROR, "未找到对应用户信息", null));
        }
    }

    @PostMapping("/my/loginUpdateByUsername/{name}")
    public ResponseEntity<Result<String>> loginUpdateByUsername(@PathVariable String name, @RequestBody Map<String, String> params) {
        User user = authService.findByName(name);
        String newname = params.get("name");
        String newphone = params.get("phone");
        int newage = Integer.parseInt(params.get("age"));
        String newaddress = params.get("address");
        String avatar = params.get("avatar");
        System.out.println(avatar);

        user.setName(newname);
        user.setPhone(newphone);
        user.setAge(newage);
        user.setAddress(newaddress);
        user.setAvatar(avatar);
        System.out.println(user);
        if (user == null) {
            return ResponseEntity.ok(new Result<>(false, StatusCode.ERROR, "用户不存在", null));
        }

        // 执行更新操作
        int rowsAffected = authService.updateByPrimaryKey(user);
        if (rowsAffected > 0) {
            return ResponseEntity.ok(new Result<>(true, StatusCode.OK, "更新成功", null));
        } else {
            return ResponseEntity.ok(new Result<>(false, StatusCode.ERROR, "更新失败", null));
        }

    }


    @PostMapping("/user/loginUpdatePassword")
    public ResponseEntity<Result<String>> updatePassword(@RequestBody Map<String, String> requestBody) {
        String username = requestBody.get("username");
        String newPassword = requestBody.get("newPassword");

        // 检查用户名是否存在
        User existingUser = authService.findByName(username);
        if (existingUser == null) {
            return ResponseEntity.ok(new Result<>(false, StatusCode.ERROR, "用户不存在", null));
        }

        // 更新用户密码
//        authService.updatePassword(existingUser, newPassword);
        existingUser.setPassword(newPassword);
        int rowsAffected = authService.update(existingUser);
//        return ResponseEntity.ok(new Result<>(true, StatusCode.OK, "更新密码成功", null));

        if (rowsAffected > 0) {
            return ResponseEntity.ok(new Result<>(true, StatusCode.OK, "更新密码成功", null));
        } else {
            return ResponseEntity.ok(new Result<>(false, StatusCode.ERROR, "更新密码失败", null));
        }
    }



    @PostMapping("/{userId}/add-dish/{dishId}")
    public ResponseEntity<Result<String>> addDishToUser(@PathVariable Long userId, @PathVariable Long dishId) {
        authService.addDishToUser(userId, dishId);
        return ResponseEntity.ok(new Result<>(true, StatusCode.OK, "添加菜品成功", "Dish added to user successfully"));
    }

//    @PostMapping("/{userId}/add-vieweddish/{dishId}")
//    public ResponseEntity<Result<String>> addViewDishToUser(@PathVariable Long userId, @PathVariable Long dishId) {
//        authService.addViewDishToUser(userId, dishId);
//        return ResponseEntity.ok(new Result<>(true, StatusCode.OK, "添加浏览过的菜品成功", "viewedDish added to user successfully"));
//    }

    @PutMapping("/{userId}/share-dish/{dishId}/with/{otherUserId}")
    public ResponseEntity<Result<String>> shareDishWithUser(@PathVariable Long userId, @PathVariable Long dishId, @PathVariable Long otherUserId) {
        authService.shareDishWithUser(userId, dishId, otherUserId);
        return ResponseEntity.ok(new Result<>(true, StatusCode.OK, "分享菜品成功", "Dish shared with user successfully"));
    }

}
